/*
 * two_dimentional_array.cpp
 *
 * Demonstrating how to define two-dimentional array in auto/static/dynamic
 * duration and to use them as function parameter.
 *
 */

#include <cstdio>


// Assigning to auto or static array.
void assign(int row, int (*array)[2]);

// Assigning to dynamic array.
void assign(int row, int column, int** array);


// Outputting auto or static array.
void output(int (*array)[2], int row);

// Outputting dynamic array.
void output(int** array, int row, int column);


int staticarray[3][2];


int main() {

    assign(3, staticarray);


    int autoarray[3][2];

    assign(3, autoarray);


    int** dynamicarray1 = new int*[3];
    for (int i = 0; i < 3; ++i) dynamicarray1[i] = new int[2];

    assign(3, 2, dynamicarray1);


    int** dynamicarray2 = new int*[3];
    int* data = new int[3*2];
    for (int i = 0; i < 3; ++i) dynamicarray2[i] = data + 2 * i;

    assign(3, 2, dynamicarray2);



    std::printf("Outputting static array...\n");
    output(staticarray, 3);


    std::printf("Outputting auto array...\n");
    output(autoarray, 3);


    std::printf("Outputting dynamic array 1...\n");
    output(dynamicarray1, 3, 2);


    std::printf("Outputting dynamic array 2...\n");
    output(dynamicarray2, 3, 2);


    delete[] data;
    delete[] dynamicarray2;

    for (int i = 0; i < 3; ++i)
        delete[] dynamicarray1[i];
    delete[] dynamicarray1;

    std::printf("\nBye...\n");
    return 0;
}



void assign(int r, int (*array)[2]) {
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < 2; ++j)
            array[i][j] = (i+1)*(j+1);
}


void assign(int r, int c, int** array) {
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < c; ++j)
            array[i][j] = (i+1)*(j+1);
}

void output(int (*array)[2], int r) {
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < 2; ++j)
            std::printf(" %2d ", array[i][j]);
        std::printf("\n");
    }
}


void output(int** array, int r, int c) {
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < 2; ++j)
            std::printf(" %2d ", array[i][j]);
        std::printf("\n");
    }
}

